package com.rat.datadictionary.service;

import com.rat.datadictionary.entity.DataDictionary;
import com.rat.datadictionary.mapper.DataDictionaryMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: Howe
 * @create: 2021-01-07 11:31
 */
@Service
public class DataDictionaryService {
    @Resource
    private DataDictionaryMapper dataDictionaryMapper;
    @Resource
    private CreateExcelTemplateService createExcelTemplateService;


    /**
     * @Description: 根据数据库和表名查询数据字典字段
     * @Param: Map
     * @Return: List<DataDictionary>
     * @Author: Howe
     * @Date: 2021/1/7 11:32
     **/
    public List<List<DataDictionary>> findDataDictionary(DataDictionary dataDictionary) {
        List<DataDictionary> dataDictionaryList = dataDictionaryMapper.findDataDictionary(dataDictionary);
        return  subTableByTableName(dataDictionaryList);
    }

    /**
     * @Description: 导出数据字典excel
     * @Param:
     * @Return:
     * @Author: Howe
     * @Date: 2021/1/7 17:42
     **/
    public void downLoadDataDictionaryExcel(HttpServletResponse response, DataDictionary dataDictionary) throws Exception {
        List<List<DataDictionary>> dataDictionaryListGroup = findDataDictionary(dataDictionary);

        String[] title = {"字段名称", "字段类型", "是否主键", "字段备注"};
        createExcelTemplateService.makeTemplate(response, title, dataDictionaryListGroup);

    }



    /**
    * @Description: 按照表的名称分组
    * @Param: dataDictionaryList
    * @Return: List<List<DataDictionary>>
    * @Author: Howe
    * @Date: 2021/1/7 19:40
    **/
    private List<List<DataDictionary>> subTableByTableName(List<DataDictionary> dataDictionaryList) {
        Map< String, List<DataDictionary>> listMap =  dataDictionaryList.stream()
                .collect(Collectors.groupingBy(DataDictionary::getTableName));
        List<List<DataDictionary>>   DataDictionaryLinkedList =  new LinkedList<>(listMap.values());
        return DataDictionaryLinkedList;
    }

}
